import React, { useState, forwardRef, useImperativeHandle } from "react";
import { Modal, Button, Checkbox, Form, Input,notification } from "antd";
import type { FormProps } from "antd";
import { useUserStore } from "@/store";
interface LoginDialogProps {
  open: boolean;
  onClose: () => void;
}
type NotificationType = 'success' | 'info' | 'warning' | 'error';
const LoginDialog = forwardRef<HTMLDivElement, LoginDialogProps>(
  (props, ref) => {
    const [open, setOpen] = useState(false);
    const [actionType, setActionType] = useState<"login" | "register">("login");
    const [form] = Form.useForm();
    const { registerAction, loginAction } = useUserStore((state) => state);
    useImperativeHandle(ref, () => ({
      show: () => {
        setOpen(true);
      },
    }));
    const loginHandle = (values:{userName:string,password:string}) => {
      loginAction(values).then((res) => {
        notification.success({
          message: '登录成功',
          description: `欢迎用户${res.userName}~`
        })
      }).catch((err) => {
        notification.error({
          message: '登录失败',
          description: err
        })
      })
    }
    const handleOk = () => {
      form.validateFields().then((values) => {
        if (actionType === "login") {
          loginHandle(values)
        } else {
          registerAction(values).then((res) => {
            loginHandle(values)
          })
        }
        setOpen(false)
        form.resetFields();
      });
    };
    const changeActionType = () => {
      setActionType(actionType === "login" ? "register" : "login");
    };
    return (
      <>
        <Modal
          title={actionType === "login" ? "登录" : "注册"}
          centered
          open={open}
          onCancel={() => {
            setOpen(false)
            form.resetFields();
          }}
          footer={[
            <Button key="action-type" onClick={changeActionType}>
              {actionType === "login" ? "去注册" : "去登录"}
            </Button>,
            <Button key="submit" type="primary" onClick={handleOk}>
              确定
            </Button>
          ]}
        >
          <Form
            name="login_form"
            form={form}
            labelCol={{ span: 4 }}
            wrapperCol={{ span: 19 }}
            style={{ maxWidth: 600 }}
            initialValues={{ remember: true }}
            autoComplete="off"
          >
            <Form.Item<FieldType>
              label="用户名"
              name="userName"
              rules={[{ required: true, message: "请输入用户名！" }]}
            >
              <Input />
            </Form.Item>

            <Form.Item<FieldType>
              label="密码"
              name="password"
              rules={[{ required: true, message: "请输入密码！" }]}
            >
              <Input.Password />
            </Form.Item>
          </Form>
        </Modal>
      </>
    );
  },
);

export default LoginDialog;
